package com.huaxin.common;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.facebook.stetho.Stetho;
import com.huamaitel.api.HMDefines;
import com.huamaitel.api.HMJniInterface;
import com.huaxin.common.cache.DiskCache;
import com.huaxin.common.event.HxIsBackgroundProcessesEvent;
import com.huaxin.common.findutils.imageloader.GlideImageLoader;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.PrefUtil;
import com.huaxin.common.utils.ToastUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.QbSdk;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by gkl on 2016/3/30.
 */
public class BaseApp extends Application {

    public static BaseApp app;
    public static final  String CREATE_ACTION = "com.huaxin.common.BaseApp.onCreate";
    private static final int    LOCATION      = 0x0001;

    private SafeHandler mHandle;
    String mAddr, city;
    LatLng mLatLng;

    private boolean login = false;
    private static ImagePicker mImagePicker;


    //华迈视频
    public static int    mUserId          = 0;
    public static int    mVideoHandle     = 0;
    public static int    mAudioHandle     = 0;
    public static int    mTalkHandle      = 0;
    public static int    mAlarmHandle     = 0;
    public static int    mRecordHandle    = 0;
    public static byte[] mCapputureHandle = null;

    public static int mLanSearchHandle = 0;

    public static HMDefines.DeviceInfo      mDeviceInfo        = null;
    public static HMDefines.ChannelCapacity mChannelCapacity[] = null;
    public static int                       serverId           = 0;
    public static int                       treeId             = 0;
    public static int                       userId             = 0;
    public static int                       curNodeHandle      = 0;
    public static int curNodeChannel;
    public static HMDefines.DeviceInfo deviceInfo = null;
    public static List<Integer> rootList;
    private static HMJniInterface jni               = null;
    public         String         mRecordPath       = ""; // The path of video record file.
    public static  String         mCapturePath      = ""; // The path of captured picture file.
    public static  String         mLoginServerError = ""; // The error message of login sever.
    public static  boolean        mIsUserLogin      = true; // Is IsUserLogin from intent

    public static final String NODE_ID      = "nodeId";
    public static final String CHANNEL      = "channel";
    public static final String VIDEO_STREAM = "video_stream";

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //组件的初始化
        app = (BaseApp) getApplicationContext();
        initSDK();
        mHandle = new SafeHandler(this);
        mHandle.sendEmptyMessage(LOCATION);

        initImagePicker();
        JPushInterface.setDebugMode(true);// 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);// 初始化jpush
        //保留最近6条通知
        JPushInterface.setLatestNotificationNumber(this, 6);
        rootList = new ArrayList<>();
        registerActivityLifecycleCallbacks(mLifecycleCallbacks);
        initTencentBugLy();
        initFaceBookStetho();

        //定义极光 通知栏样式
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
        builder.statusBarDrawable = R.drawable.icon_logo;
        builder.notificationFlags = Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(1, builder);


        initTencentTBS();
    }

    /**
     * 初始腾讯TBS
     */
    private void initTencentTBS() {
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean b) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + b);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };

        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
        //文件下载，异常处理
       // ExceptionHandler.getInstance().initConfig(this);
    }

    /**
     * 初始化facebook Stetho
     */
    private void initFaceBookStetho() {
        Stetho.initializeWithDefaults(this);
    }

    /* Bugly SDK初始化
       * 参数1：上下文对象
       * 参数2：APPID，平台注册时得到,注意替换成你的appId
       * 参数3：是否开启调试模式，调试模式下会输出'CrashReport'tag的日志
       */
    private void initTencentBugLy() {
        CrashReport.initCrashReport(getApplicationContext(), "bf172d6ae2", true);
    }

    /**
     * @desc 华迈sdk
     * @author songxf
     * created at 2017/7/18 11:18
     */
    public static HMJniInterface getJni() {
        if (null == jni) {
            jni = new HMJniInterface();
        }
        return jni;
    }

    /**
     * @desc 初始化 ImagePicker
     * @author songxf
     * created at 17-6-27 下午3:18
     */
    private void initImagePicker() {
        mImagePicker = ImagePicker.getInstance();
        mImagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        mImagePicker.setShowCamera(true);                      //显示拍照按钮
        mImagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        mImagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        //imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        mImagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        mImagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        mImagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        mImagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        mImagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    public static ImagePicker getImagePicker() {
        if (mImagePicker != null) {
            return mImagePicker;
        }
        return null;
    }


    private void initSDK() {
        SDKInitializer.initialize(this);
        BaseConfig.parseProps(this, R.raw.baseconfig);
        RequestHelper.init(this);
        DiskCache.init(this);
        PrefUtil.init(this);
        ToastUtil.init(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterActivityLifecycleCallbacks(mLifecycleCallbacks);
    }

    public boolean isLogin() {
        return login;
    }

    LocationClient         mLocationClient;
    private class SafeHandler extends Handler {
        WeakReference<BaseApp> weakReference;

        SafeHandler(BaseApp app) {
            weakReference = new WeakReference<>(app);
        }

        @Override
        public void handleMessage(Message msg) {
            if (weakReference == null || weakReference.get() == null)
                return;
            switch (msg.what) {
                case LOCATION:
                    if (mLocationClient == null) {
                        mLocationClient = new LocationClient(weakReference.get()); // 声明LocationClient类
                        mLocationClient.registerLocationListener(mBDLocationListener); // 注册监听函数
                        LocationClientOption option = new LocationClientOption();
                        option.setScanSpan(1000 * 120);//2分钟一次
                        option.setOpenGps(true);// 打开gps
                        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度，默认值gcj02
                        option.setIsNeedAddress(true);
                        option.setIsNeedLocationDescribe(true);
                        mLocationClient.setLocOption(option);
                    }
                    mLocationClient.start();
                    break;
            }
        }
    }

    private BDLocationListener mBDLocationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null)
                return;
            mLatLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            city = bdLocation.getCity();
            mAddr = bdLocation.getCity() + bdLocation.getDistrict() + bdLocation.getStreet() + bdLocation.getStreetNumber();
            mLocationClient=null;
        }
    };

    public static String getAddrStr() {
        if (app == null || app.mAddr == null)
            return null;
        return app.mAddr;
    }

    public static LatLng getLatLng() {
        if (app == null || app.mLatLng == null)
            return null;
        return app.mLatLng;
    }

    public static String getCity() {
        if (app == null || app.city == null)
            return null;
        return app.city;
    }

    public static List<Activity> getCreatedActivities() {
        return mActivityList;
    }

    private static List<Activity> mActivityList = new ArrayList<>();

    private int mFinalCount;
    /**
     * 监听所有activity的生命周期
     */
    private ActivityLifecycleCallbacks mLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            mActivityList.add(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {
            mFinalCount++;
            if (mFinalCount == 1) {//说明是从后台到前台
                EventBus.getDefault().post(new HxIsBackgroundProcessesEvent(false));
            }
        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {
            mFinalCount--;
            if (mFinalCount == 0) {//说明是从前台到后台
                EventBus.getDefault().post(new HxIsBackgroundProcessesEvent(true));
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            mActivityList.remove(activity);
        }
    };
}
